import {createRouter, createWebHashHistory} from "vue-router";
import {getAdminToken} from "@/utils/auth";
import {useAdminStore} from "@/store/admin";
import miProgress from "@/utils/nprogress";
import site from "@/router/modules/site";

const routes : any = [
    {
        path: '/',
        component: () => import("@/layout/index.vue"),
        redirect: 'index',
        name:'layout',
        children:[
            {
                path: 'index',
                component: () => import('@/views/index/index.vue'),
                name: 'index',
                meta: {title: '首页', icon: 'dashboard', affix: true}
            },
            // {
            //     path: '/:catchAll(.*)',
            //     name: '404',
            //     component: () => import('@/views/error/404.vue')
            // }
        ]
    },
    {
        path: '/login',
        component: () => import("@/views/public/Login.vue")
    },
    ...site
    // {
    //     path: '/:catchAll(.*)',
    //     name: '404',
    //     component: () => import('@/views/error/404.vue')
    // }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

router.beforeEach(async (to, from) => {

    miProgress.start()
    const token = getAdminToken()
    const toPath = to.path
    const loginPath = '/login'
    const adminStore = useAdminStore()

    // 已登录
    if (token) {


        console.log("loginToken", token)

        // 访问了登录页
        if(toPath == loginPath) return {path: '/index'}

        if (adminStore.menus.length === 0){
            // 初始化登录后的数据
            await adminStore.init()
            return {...to, replace:true};
        }

    }else{  // 未登录

        if (toPath != loginPath){
            return {path: loginPath}
        }
    }

    return true
})


router.afterEach(() => {
    miProgress.done()
})

export default router
